<?php
class ArrayExt {
	public function addIndex($aArray) {
		while ( ($aRow = each ( $aArray )) !== false ) {
			$aIndexArray [] = array ('key' => $aRow ['key'], 'value' => $aRow ['value'] );
		}
		return $aIndexArray;
	}
	
	public function merge($aArray1, $aArray2) {
		$aResult = array ();
		foreach ( $aArray1 as $sKey => $sValue ) {
			if (is_array ( $sValue ) && is_array ( $aArray2 [$sKey] )) {
				$aResult [$sKey] = self::merge ( $sValue, $aArray2 [$sKey] );
				unset ( $aArray2 [$sKey] );
			} elseif ($sValue === $aArray2 [$sKey]) {
				$aResult [$sKey] = $sValue;
				unset ( $aArray2 [$sKey] );
			} else {
				$aResult [$sKey] = $sValue;
			}
		}
		
		foreach ( $aArray2 as $sKey => $sValue ) {
			if (! array_key_exists ( $sKey, $aResult )) {
				$aResult [$sKey] = $sValue;
			} else {
				$aResult [] = $sValue;
			}
		}
		return $aResult;
	}
	
	public function getValue($aData) {
		$aResult = array ();
		foreach ( $aData as $sRow ) {
			if (is_array ( $sRow )) {
				$aResult = array_merge ( $aResult, self::getValue ( $sRow ) );
			} else {
				$aResult [] = $sRow;
			}
		}
		return $aResult;
	}
	
	public function sortCount($aData, $sOrder = 'asc') {
		foreach ( $aData as $sRow ) {
			$sId = md5 ( $sRow );
			$aMap [$sId] = $sRow;
			$aTmp [$sId] ++;
		}
		if ($sOrder == 'asc') {
			asort ( $aTmp );
		} else {
			arsort ( $aTmp );
		}
		
		foreach ( $aTmp as $sKey => $iRow ) {
			$aResult [] = $aMap [$sKey];
		}
		return $aResult;
	}
	
	public function arrayIntersection($aArray1, $aArray2) {
		$aResult = array ();
		foreach ( $aArray1 as $sKey => $sValue ) {
			if (is_array ( $sValue ) && is_array ( $aArray2 [$sKey] )) {
				$aTmpResult = self::arrayIntersection ( $sValue, $aArray2 [$sKey] );
				if (count ( $aTmpResult )) {
					if (is_string ( $sKey )) {
						$aResult [$sKey] = $aTmpResult;
					} else {
						$aResult [] = $aTmpResult;
					}
				}
				unset ( $aArray2 [$sKey] );
			} else {
				$sKey = array_search ( $sValue, $aArray2 );
				if ($sKey !== false) {
					$aResult [] = $sValue;
					unset ( $aArray2 [$sKey] );
				}
			}
		}
		return $aResult;
	}
}
?>